<?php
namespace App\Http\Controllers\Manage\Movie;

use App\Http\Controllers\Manage\CommonController;
use App\Http\Requests\MoviePostRequest;
use App\Http\Requests\Request;
use App\Model\Movie\Movie;
use App\Model\Movie\MovieCategory;
use App\Model\Movie\MovieMapCategory;
use Illuminate\Support\Facades\DB;

class MovieController extends CommonController
{
    /**
     * 查看影视
     * @return mixed
     */
    public function index()
    {
        $field = [
            'id' => '影视编号',
            'title' => '影视名称',
            'type' => '影视类型',
            'create_time' => '发布时间',
            'status' => '状态',
        ];
        $viewData = [];
        $viewData['title'] = '影视管理';
        # 查询字段
        $viewData['field'] = $field;
        # 列表取值范围替换
        $range = [
            'status' => [ 0 =>'下架', 1 => '上架'],
            'type' => movieType()
        ];
        $viewData['range'] = $range;
            # 列表操作菜单
        $viewData['option_title'] = [
            'plus' => [
                'title' => '发布新影视',
                'route' => route('manage.movie.resource.create')
            ]
        ];
        # 行表操作菜单
        $page = $this->request->input('page', 1);
        $viewData['option_row'] = [
            'edit' => [
                'title' => '编辑',
                'route' => 'manage.movie.resource.edit',
                'param' =>   [
                    'page' => $page
                ]
            ],
            'eye' => [
                'title' => '上架',
                'route' => 'manage.movie.status',
                'where' => [
                    ['name' => 'status', 'condition' => '=', 'value' => '0']
                ]
            ],
            'eye-slash' => [
                'title' => '下架',
                'route' => 'manage.movie.status',
                'where' => [
                    ['name' => 'status', 'condition' => '=', 'value' => '1']
                ]
            ],
            'category' => [
                'title' => '分类关联',
                'load' => 'manage.movie.map.category'
            ],
            'trash' => [
                'title' => '删除',
                'route' => 'manage.movie.resource.destroy'
            ]
        ];
        # 页面模态对话框
        $viewData['option_modal'] = [
            'trash' => [
                'method' => 'DELETE',
                'title' => '删除影视',
                'msg' => '确定要删除该电影吗'
            ],
        ];
        # 查询记录
        $movie = Movie::where('is_delete', 0);
        $viewData['list'] = $this->constraintSelect($movie, $field, $range);
        # 渲染视图
        return view('manage.table', $viewData);
    }

    /**
     * 删除影视
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $movie = Movie::find($id);
        $movie->is_delete = 1;
        $movie->update_user = $this->user['id'];
        $this->log(json_encode('manage:' . $this->user['id'] . ' remove movie:' . $id . ' time:' . currentTime()), 'info', 'product_destroy');
        if ($movie->save()) {
            return redirect()->back()->with('success', '影视删除成功!');
        }
        return redirect()->back()->with('error', '影视删除失败!');
    }

    /**
     * 创建影视页面
     * @return mixed
     */
    public function create()
    {
        # 表单元素
        $param = [];
        $param['type'] = [
            'name' => '影视类型',
            'type' => 'select',
            'range' => movieType(),
            'col' => '3'
        ];
        $param['title'] = [
            'name' => '影视名称',
            'type' => 'text',
            'col' => '9'
        ];
        $param['thumb'] = [
            'name' => '影视缩略预览图（建议256×256像素）',
            'type' => 'thumb',
            'col' => '3',
            'accept' => 'image',
            'ratio' => '1'
        ];
        foreach ($param as $key => $value) {
            $param[$key]['value'] = $this->request->old($key);
        }
        $viewData = [];
        $viewData['title'] = '发布新影视';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.movie.resource.store');
        $viewData['form_method'] = 'POST';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回影视列表',
                'type' => 'button',
                'route' => route('manage.movie.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset'
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }

    /**
     *
     * 创建影视页面
     *
     * @param MoviePostRequest $request
     * @return mixed
     */
    public function store(MoviePostRequest $request)
    {
        $this->request->flash();
        if (!$this->request->has('title')) {
            return redirect()->back()->with('error', '请填写影视名称');
        }
        if (!$this->request->has('thumb')) {
            return redirect()->back()->with('error', '必须上传影视缩略图');
        }
        $thumb = $this->request->input('thumb');
        $thumb = $this->uploadBase64Image($thumb, 'movie');
        if (!$thumb) {
            return redirect()->back()->with('error', '影视预览图文件上传失败!');
        }
        # 插入新数据
        $movie = new Movie();
        $movie->title = $this->request->input('title');
        $movie->type = $this->request->input('type');
        $movie->thumb = $thumb;
        $movie->status = 1;
        $movie->create_user = $this->user['id'];
        if ($movie->save()) {
            # 创建成功后跳转到影视详细介绍编辑页
            return redirect()->route('manage.movie.resource.index')->with('success', '影视创建成功!');
        }
        return redirect()->back()->with('error', '影视创建失败!');
    }

    /**
     * 修改管理员信息页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $movie = Movie::find($id);
        # 表单元素
        $param = [];
        $param['type'] = [
            'name' => '影视类型',
            'type' => 'select',
            'col' => '3',
            'range' => movieType(),
            'value' => $movie->type
        ];
        $param['title'] = [
            'name' => '影视名称',
            'type' => 'text',
            'col' => '9',
            'value' => $movie->title
        ];
        $param['thumb'] = [
            'type' => 'thumb',
            'col' => '3',
            'name' => '影视缩略预览图（建议256×256像素）',
            'accept' => 'image',
            'value' => $this->domain . $this->path['movie'] . $movie->thumb,
            'ratio' => '1',
        ];
        foreach ($param as $key => $value) {
            if ($this->request->old($key)) $param[$key]['value'] = $this->request->old($key);
        }
        $viewData = [];
        $viewData['title'] = '修改影视信息';
        $viewData['nav'] = $this->navTab('movie', 'main', ['id' => $id]);
        $viewData['form'] = $this->form($param);
        $page = $this->request->input('page', 1);
        $viewData['form_url'] = route('manage.movie.resource.update', ['id' => $id, 'page' => $page]);
        $viewData['form_method'] = 'PUT';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回影视列表',
                'type' => 'button',
                'route' => route('manage.movie.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset'
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        # 渲染视图
        return view('manage.form', $viewData);
    }

    /**
     *
     * 修改管理员信息操作
     *
     * @param MoviePostRequest $request
     * @param $id
     * @return mixed
     */
    public function update(MoviePostRequest $request, $id)
    {
        $movie = Movie::find($id);
        if (!$movie) {
            return redirect()->back()->with('error', '影视编号不存在');
        }
        $this->request->flash();
        if (!$this->request->has('title')) {
            return redirect()->back()->with('error', '请填写影视名称');
        }
        # 修改影视预览图
        $thumb = null;
        if ($this->request->has('thumb')) {
            $thumb = $this->request->input('thumb');
            $thumb = $this->uploadBase64Image($thumb, 'movie');
            if (!$thumb) {
                return redirect()->back()->with('error', '影视预览图文件上传失败!');
            }
        }
        # 更新数据
        $movie->title = $this->request->input('title');
        $movie->type = $this->request->input('type');
        if ($thumb) $movie->thumb = $thumb;
        if (!$movie->save()) {
            return redirect()->back()->with('error', '影视修改成功');
        }
        $page = $this->request->input('page', 1);
        $param = [
            'page' => $page
        ];
        return redirect()->route('manage.movie.resource.index', $param)->with('success', '影视修改成功');
    }

    /**
     *
     * 影视上架下架
     *
     * @param $id
     * @return mixed
     */
    public function status($id)
    {
        $movie = Movie::find($id);
        if(!$movie) {
            return redirect()->back()->with('error', '影视信息异常！');
        }
        $status = ($movie->status == '1') ? '0' : '1';
        $msg = ($movie->status == '1') ? '上架' : '下架';
        $movie->status = $status;
        if(!$movie->save()) {
            return redirect()->back()->with('error', '影视' . $msg . '失败！');
        }
        return redirect()->route('manage.movie.resource.index')->with('success', '影视' . $msg . '成功！');
    }

    /**
     *
     * 获取分类关联
     *
     * @param $id
     */
    public function getMap($id)
    {
        $movieCategory = MovieCategory::keyName();
        $mapValue = MovieMapCategory::where('movie_id', $id)->lists('category_id')->implode(',');
        # 表单元素配置
        $param = [
            'category' => [
                'type' => 'checkbox',
                'col' => '12',
                'name' => '分类关联',
                'range' => $movieCategory,
                'value' => $mapValue
            ],
        ];
        $viewData = [];
        $viewData['form_title'] = '影视分类关联';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.movie.map.category', ['movie_id' => $id]);
        $viewData['form_method'] = 'POST';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回影视列表',
                'type' => 'button',
                'route' => route('manage.movie.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset'
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        # 渲染视图
        return view('manage.lib.form', $viewData);
    }
    
    /**
     *
     * 获取分类关联
     *
     * @param $id
     */
    public function setMap($id)
    {
        $category = $this->request->input('category');
        if ($category) {
            # 查询已有影视分类关联记录
            $map = MovieMapCategory::where('movie_id', $id)->lists('category_id')->toArray();
            # 过滤已有的角色关联数据，并获取需要删除的角色关联数据
            # 需要添加是数据
            $add = array_diff($category, $map);
            # 执行添加记录
            $data = array();
            foreach ($add as $val) {
                $data[] = [
                    'movie_id' => $id,
                    'category_id' => $val
                ];
            }
            MovieMapCategory::insert($data);
            # 需要删除的数据
            $del = array_diff($map, $category);
            # 执行删除记录
            MovieMapCategory::where('movie_id', $id)->whereIn('category_id', $del)->delete();
            return redirect()->back()->with('success', '影视分类关联修改成功!');
        }
        return redirect()->back()->with('error', '影视分类关联修改失败!');
    }
}
